import path from 'path'
import { NodeSSH } from 'node-ssh'
import { deployConfig } from './config.js'

async function deploy(source, target) {
  const ssh = new NodeSSH()
  await ssh.connect(deployConfig)

  const result = await ssh.execCommand('ls', {
    cwd: 'var/www'
  })
  console.log(`result.stdout ==> ${result.stdout}`);
  const isHasBackup = result.stdout.includes('dist.bak')
  if (isHasBackup) {
    await ssh.execCommand('rm -rf dist.bak', {
      cwd: 'var/www'
    })
  }

  await ssh.execCommand("mv dist dist.bak", {
    cwd: 'var/www'
  })
  await ssh.putDirectory(path.resolve("./dist"), "var/www/dist")

  ssh.dispose()
}

module.exports = {
  deploy
}
